package com.chao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chao.entity.Student;
import com.chao.entity.Teacher;
import com.chao.entity.User;
import com.chao.service.StudentService;
import com.chao.service.TeacherService;
import com.chao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@Validated
public class RegistController {

    @Autowired
    UserService userService;
    @Autowired
    TeacherService teacherService;
    @Autowired
    StudentService studentService;

    // 返回注册 页面
    @GetMapping("/regist.html")
    public String registration(Model model,
                               @RequestParam(defaultValue = "") String msg) {
        model.addAttribute("msg",msg);
        return "registration";
    }

    // 注册账号
    @PostMapping("/regist")
    public String regist(@Validated User user,
                         RedirectAttributes ra) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("u_id",user.getUId());
        boolean exists = userService.getBaseMapper().exists(userQueryWrapper);
        if(exists) {
            ra.addAttribute("msg","该账号已经注册");
            return "redirect:/regist.html";
        }
        // 需要验证 学号真实性
        if (user.getPrivilege() == 1) {
            studentQueryWrapper.clear();
            studentQueryWrapper.eq("s_id", user.getUId()).eq("s_name", user.getUsername());
            Student student = studentService.getOne(studentQueryWrapper);
            if (student != null) {
                userService.save(user);
                ra.addAttribute("msg","注册成功");
                return "redirect:/regist.html";
            }
        } else {
            teacherQueryWrapper.clear();
            teacherQueryWrapper.eq("t_id", Integer.parseInt(user.getUId())).eq("t_name", user.getUsername());
            Teacher teacher = teacherService.getOne(teacherQueryWrapper);
            if(teacher != null) {
                userService.save(user);
                ra.addAttribute("msg","注册成功");
                return "redirect:/regist.html";
            }
        }
        ra.addAttribute("msg","注册失败");
        return "redirect:/regist.html";
    }

}
